package components

import (
	"errors"
	"gitee.com/dashengbuqi/luckdraw/models"
	"sync"
)

var (
	mu         sync.Mutex
	normalUser = make(map[int]*models.LuckdrawUser)
	drawnUser  = make(map[int]*models.LuckdrawUser)
)

func init() {
	mu.Lock()
	defer mu.Unlock()
	u := models.GetUsers()
	if len(u) > 0 {
		for _, user := range u {
			normalUser[user.Id] = user
		}
	}
}

//获取有效用户
func GetNormalPool() map[int]*models.LuckdrawUser {
	return normalUser
}

func GetAllUserPool() map[int]*models.LuckdrawUser {
	result := normalUser
	if len(drawnUser) > 0 {
		for num, lu := range drawnUser {
			result[num] = lu
		}
	}
	return result
}

//获奖用户
func GetDrawnPool() map[int]*models.LuckdrawUser {
	return drawnUser
}

//废弃当前用户的抽奖
func Discard(num int) error {
	if num == 0 {
		return errors.New("未获取到放弃奖品的用户编号")
	}
	if len(drawnUser) == 0 {
		return errors.New("暂时还没有获奖用户")
	}
	user, ok := drawnUser[num]
	if ok == false {
		return errors.New("当前用户不是获取用户")
	}
	mu.Lock()
	defer mu.Unlock()
	//删除幸运名单
	delete(drawnUser, num)
	//获奖名单减1
	user.Prize.Winner--
	//如果用户失效则需要返回正常状态
	if user.Prize.Valid == false {
		user.Prize.Valid = true
	}
	//用户能中奖的次数加回来
	user.Luck_times++
	if _, ok := normalUser[user.Id]; ok == false {
		normalUser[user.Id] = user
	}
	return nil
}

//中奖者
func Drawn(nums []int) error {
	if len(nums) == 0 {
		return errors.New("未找到获奖名单")
	}
	prize := models.FindDrawLevel()
	if prize == nil {
		return errors.New("还没有中奖吗？一起等待神秘大奖！")
	}
	if prize.Winner >= prize.Total {
		return errors.New("奖品已抽完了,或者还有神秘大奖等着你!")
	}
	n := prize.Total - prize.Winner
	if len(nums) > n {
		nums = nums[0 : n-1]
	}
	users := models.GetUsersByNum(nums)
	if users == nil {
		return errors.New("未获取的幸运用户")
	}
	mu.Lock()
	defer mu.Unlock()
	for _, num := range nums {
		if _, okey := normalUser[num]; okey {
			normalUser[num].Luck_times--
			drawnUser[num] = normalUser[num]
			prize.Winner++
			if prize.Winner == prize.Total {
				prize.Valid = false
			}
			drawnUser[num].Prize = prize
			if normalUser[num].Luck_times == 0 {
				delete(normalUser, num)
			}
		}
	}
	return nil
}
